<template>
  <div class="spurs-dialog">
    <el-dialog
      v-model="dialogVisible"
      :append-to-body="true"
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      draggable
    >
      <SpursForm
        ref="spursFormRef"
        v-bind="formConfig"
        :modelValue="modelValue"
        :rules="rules"
      >
        <template #special>
          <div class="special">
            <el-upload
              action="#"
              :http-request="customRequest"
              :file-list="fileList"
              list-type="picture-card"
              :before-upload="beforeUpload"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :on-error="handleError"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisibleImageUrl">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </div>
        </template>
      </SpursForm>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">取消</el-button>
          <el-button type="primary" @click="saveSubmit"> 确 定 </el-button>
          <slot name="footer"></slot>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import SpursForm from "@/components/SpursForm/index.vue";
import type { FormInstance, FormRules } from "element-plus";
import cloneDeep from "lodash/cloneDeep";
import orderApi from "@/api/order";
import { ElMessage } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
const spursFormRef = ref<any>();
const rules = reactive<FormRules>({
  pName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  pBrand: [{ required: true, message: "请输入商品品牌", trigger: "blur" }],
  pSpecifications: [
    { required: true, message: "请输入商品规格", trigger: "blur" },
  ],
  // pIntroduce: [
  //   { required: true, message: '请输入商品简介', trigger: 'blur' }
  // ],
  pNumber: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
  pPrice: [{ required: true, message: "请输入商品单价", trigger: "blur" }],
  status: [{ required: true, message: "请输入商品单价", trigger: "change" }],
  pType: [{ required: true, message: "请输入商品单价", trigger: "change" }],
});
const dialogImageUrl = ref("");
const dialogVisibleImageUrl = ref(false);
const fileList = ref<UploadUserFile[]>([
  {
    name: "food.jpeg",
    url: "https://img0.baidu.com/it/u=3532911324,2007152132&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=738",
  },
]);
// 上传前回调
const beforeUpload = (file: any) => {
  const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png";
  const fileSizeMB = file.size / (1024 * 1024);
  const isLt5MB = fileSizeMB < 5;

  if (!isJPGorPNG) {
    ElMessage.error("只能上传JPG/PNG格式的图片!");
    return false;
  }
  if (!isLt5MB) {
    ElMessage.error("图片大小不能超过5MB!");
    return false;
  }
  return true;
};
// 移除文件的回调
const handleRemove = (file: any, fileList: any) => {
  console.log("移除文件:", file, fileList);
};
// 成功回调
const handleSuccess = (response: any, file: any, fileList: any) => {
  console.log("上传成功:", response, file, fileList);
};
// 失败回调
const handleError = (err: any, file: any, fileList: any) => {
  console.error("上传失败:", err, file, fileList);
};
const customRequest = async (options: any) => {
  const { file, onProgress, onSuccess, onError } = options;

  const formData = new FormData();
  formData.append("file", file);

  try {
    // const res = await productApi.fileUpload(formData)
  } catch (err) {
    onError(err);
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addEditFun();
    } else {
      spursFormRef.value.ruleFormRef.clearValidate();
    }
  });
};
const addEditFun = async () => {
  let res = null;
  if (props.title == "新增") {
    res = await orderApi.addOrder(modelValue.value);
  } else {
    const id = props.formData.id;
    res = await orderApi.editOrder(id, modelValue.value);
  }
  emit("saveSubmit", res);
};
const modelValue = ref({});
const props = defineProps({
  visible: { type: Boolean, default: false },
  title: { type: String, default: "新增" },
  formData: { type: Object, default: {} },
});
const emit = defineEmits(["update:visible", "saveSubmit"]);
let dialogVisible = ref(props.visible);
watch(
  () => props.visible,
  (newValue) => {
    dialogVisible.value = newValue;
    if (newValue) {
      modelValue.value = cloneDeep(props.formData);
    } else {
      modelValue.value = {};
    }
    console.log(modelValue.value, "modelValuemodelValue");
  }
);
watch(
  () => dialogVisible.value,
  (newValue) => {
    emit("update:visible", newValue);
  }
);
const close = () => {
  dialogVisible.value = false;
  spursFormRef.value.ruleFormRef.clearValidate();
};
const saveSubmit = () => {
  submitForm(spursFormRef.value.ruleFormRef);
};
</script>

<style scoped></style>
